import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({
    showSpinner: false
}) // NProgress Configuration  禁用进度环
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
let isPush = false
let endTime = Date.now()
let methods = ['push', 'go', 'replace', 'forward', 'back']

document.addEventListener('touchend', () => {
    endTime = Date.now()
})
methods.forEach(key => {
    let method = router[key].bind(router)
    router[key] = function(...args) {
        isPush = true
        method.apply(null, args)
    }
})


router.beforeEach(function(to, from, next) {
    NProgress.start()
    
    const toIndex = history.getItem(to.path)
    const fromIndex = history.getItem(from.path)
    console.log(toIndex)
    if (toIndex) {
        if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
            console.log("右")
            store.commit('UPDATE_DIRECTION', {
                direction: 'forward'
            })
        } else {
            console.log("左")
            // 判断是否是ios左滑返回
            if (!isPush && (Date.now() - endTime) < 377) {
                store.commit('UPDATE_DIRECTION', {
                    direction: ''
                })
            } else {
                store.commit('UPDATE_DIRECTION', {
                    direction: 'reverse'
                })
            }
        }
    } else {
        ++historyCount
        history.setItem('count', historyCount)
        to.path !== '/' && history.setItem(to.path, historyCount)
        store.commit('UPDATE_DIRECTION', {
            direction: ''
        })
    }
    next()
})
router.afterEach((to, from, next) => {

    NProgress.done() // finish progress bar
})